package com.dshore.messagecenter.util;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.http.Consts;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;


public class HttpUtil {
	
	private static CloseableHttpClient httpclient = HttpClients.createDefault();
	
    /**
     * 发送HttpPost请求
     * @param url
     * @param map
     * @return
     */
    public static String sendPost(String url, Map<String, Object> map) {
    	HttpPost httppost = new HttpPost(url);
    	if (map != null) {
            List<NameValuePair> formparams = new ArrayList<NameValuePair>();
            for (Map.Entry<String, Object> entry : map.entrySet()) {
                formparams.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString()));
            }
            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, Consts.UTF_8);    
            httppost.setEntity(entity);
    	}
        
        try {
        	CloseableHttpResponse response = httpclient.execute(httppost);
        	if (response != null) {
        		return EntityUtils.toString(response.getEntity());
        	} else {
        		return null;
        	}
        } catch (IOException e) {
        	System.out.println("catch error");
            e.printStackTrace();
        	return null;
        }
    }
}